package TMS.src;

import java.util.*;
import java.io.*;


public class Commodity implements Serializable {
    public static int numOfCommodity = 0;
    private String commodityName;
    private double commodityPrice;
    private int commodityNum;
    private String commodityId;
    private boolean commodityStatus;
    private String shopId;
    private User master;

    public Commodity() {
    }

    public Commodity(String shopId, String commodityName, double commodityPrice, int commodityNum) {
        //numOfCommodity++;
        this.shopId = shopId;
        this.commodityName = commodityName;
        this.commodityPrice = commodityPrice;
        this.commodityNum = commodityNum;
        this.commodityStatus = true;
    }

    String getCommodityName() {
        return this.commodityName;
    }

    void setCommodityName(String name) {
        this.commodityName = name;
    }

    double getCommodityPrice() {
        return this.commodityPrice;
    }

    void setCommodityPrice(double price) {
        this.commodityPrice = price;
    }

    int getCommodityNum() {
        return commodityNum;
    }

    void setCommodityNum(int num) {
        this.commodityNum = num;
    }

    String getCommodityId() {
        return this.commodityId;
    }

    void setCommodityId(String id) {
        this.commodityId = id;
    }

    String getShopId() {
        return this.shopId;
    }

    void setShopId(String id) {
        this.shopId = id;
    }

    void setCommodityStatus(boolean status) {
        this.commodityStatus = status;
    }

    boolean getCommodityStatus() {
        return this.commodityStatus;
    }

    int getNumOfCommodity() {
        return numOfCommodity;
    }

    User getMaster() {
        return this.master;
    }

    void setMaster(User master) {
        this.master = master;
    }

    Map<String, Shop> sortListCommodity_shop(Map<String, Shop> map) {
        //HashMap无序；LinkedHashMap有序）
        LinkedHashMap<String, Shop> linkedHashMap = new LinkedHashMap<>();
        Set<Map.Entry<String, Shop>> entrySet = map.entrySet();
        List<Map.Entry<String, Shop>> list = new ArrayList<>(entrySet);
        list.sort(Comparator.comparingInt(o -> Integer.parseInt(o.getKey().substring(2))));
        list.forEach(item -> linkedHashMap.put(item.getKey(), item.getValue()));
        return linkedHashMap;
    }

    Map<String, Commodity> sortListCommodity(Map<String, Commodity> map) {
        //HashMap无序；LinkedHashMap有序）
        LinkedHashMap<String, Commodity> linkedHashMap = new LinkedHashMap<>();
        Set<Map.Entry<String, Commodity>> entrySet = map.entrySet();
        List<Map.Entry<String, Commodity>> list = new ArrayList<>(entrySet);
        list.sort(Comparator.comparingInt(o -> Integer.parseInt(o.getValue().getCommodityId().substring(2))));
        list.forEach(item -> linkedHashMap.put(item.getKey(), item.getValue()));
        return linkedHashMap;
    }

    Map<String, Commodity> sortSearchCommodity(Map<String, Commodity> map) {//string为shopId+commodityId HashMap无序；LinkedHashMap有序）
        LinkedHashMap<String, Commodity> linkedHashMap = new LinkedHashMap<>();
        Set<Map.Entry<String, Commodity>> entrySet = map.entrySet();
        List<Map.Entry<String, Commodity>> list = new ArrayList<>(entrySet);
        list.sort((o1, o2) -> {
            int a = o1.getKey().indexOf("C");
            int b = o2.getKey().indexOf("C");
            // o1-o2是正序；o2-o1是倒序；
            int i = Integer.parseInt(o1.getKey().substring(2, a)) - Integer.parseInt(o2.getKey().substring(2, b));
            if (i == 0) { //当i==0时说明上面的排序条件相等了，你可以通过其他条件来排序这个相等的元素；
                return Integer.parseInt(o1.getKey().substring(a + 2)) - Integer.parseInt(o2.getKey().substring(b + 2));
            }
            return i;
        });
        list.forEach(item -> linkedHashMap.put(item.getKey(), item.getValue()));
        return linkedHashMap;
    }

    String PutCommodity(String[] cmd) {
        if (cmd.length == 5) {//上架新商品
            String shopId = cmd[1];
            String commodityName = cmd[2];
            String price_pattern = "^0.[0-9]{1,2}$|^[1-9][0-9]{0,7}.[0-9]{1,2}$|^[1-9][0-9]{0,7}$";
            String wrong_pattern = "^0.0$|^0.00$";
            double commodityPrice = 0;
            if (cmd[3].matches(price_pattern) && !cmd[3].matches(wrong_pattern)) {
                commodityPrice = Double.parseDouble(cmd[3]);
            } else {
                return "Illegal commodity price";
            }
            int commodityNum;
            if (cmd[4].matches("^[1-9]+[0-9]*"))
                commodityNum = Integer.parseInt(cmd[4]);
            else
                return "Illegal commodity quantity";
            User current_user = Const.current_user;
            String identity = current_user != null ? current_user.getIdentity() : null;
            boolean not_logged_in = !Const.logged_in;
            boolean identity_illegal = identity != null ? !identity.equals("Merchant") : false;
            boolean shopId_illegal = !shopId.matches("^S-[1-9]\\d*$");
            boolean commodityName_illegal = !commodityName.matches("^[a-zA-Z][a-zA-Z-_]{0,49}$");
            boolean commodityPrice_illegal = commodityPrice <= 0 || commodityPrice > 99999999.99;
            boolean commodityNum_illegal = cmd[4].charAt(0) == '0' || commodityNum <= 0;
            boolean shop_not_existed = false;
            if (!Const.allShop_existed.containsKey(shopId))
                shop_not_existed = true;
            else if (Const.allShop_existed.get(shopId).getMaster() != current_user)
                shop_not_existed = true;

            if (not_logged_in) {
                return "Please log in first";
            } else if (identity_illegal) {
                return "Permission denied";
            } else if (shopId_illegal) {
                return "Illegal shop id";
            } else if (shop_not_existed) {
                return "Shop id not exists";
            } else if (commodityName_illegal) {
                return "Illegal commodity name";
            } else if (commodityPrice_illegal) {
                return "Illegal commodity price";
            } else if (commodityNum_illegal) {
                return "Illegal commodity quantity";
            } else {
                numOfCommodity++;
                Commodity commodity = new Commodity(shopId, commodityName, commodityPrice, commodityNum);
                commodity.setCommodityId("C-" + numOfCommodity);
                commodity.setMaster(current_user);

                Const.allShop_existed.get(shopId).getCommodities().put(commodity.getCommodityId(), commodity);
                Const.allCommodities_existed.put(commodity.getShopId() + commodity.getCommodityId(), commodity);
                Const.existed_commodities.put(commodity.getCommodityId(), commodity);
                //对commodity排序

                return "Put commodity success (commodityId: " + commodity.getCommodityId() + ")";
            }
        } else if (cmd.length == 4) {//补货 或 者新商店旧货物
            String shopId = cmd[1];
            String commodityId = cmd[2];
            int commodityNum = 0;
            if (cmd[3].matches("^[1-9]+[0-9]*"))
                commodityNum = Integer.parseInt(cmd[3]);
            else
                return "Illegal commodity quantity";
            User current_user = Const.current_user;
            String identity = current_user != null ? current_user.getIdentity() : null;
            Commodity existed_commodity = null;
            boolean identity_illegal = current_user == null ? true : !identity.equals("Merchant");
            boolean shopId_illegal = !shopId.matches("^S-[1-9]\\d*$");
            boolean commodityId_illegal = !commodityId.matches("^C-[1-9]\\d*$");
            boolean commodity_not_existed = true;
            boolean commodityNum_illegal = cmd[3].charAt(0) == '0' || commodityNum <= 0;
            boolean shop_not_existed = false;

            if (!Const.allShop_existed.containsKey(shopId))//商店是否存在
                shop_not_existed = true;
            else if (Const.allShop_existed.get(shopId).getMaster() != current_user)//用户是商店的主人
                shop_not_existed = true;

            for (Commodity commodity : Const.existed_commodities.values()) {//对于未封禁商品
                if (Objects.equals(commodityId, commodity.getCommodityId())) {//找到那个Id匹配的商品
                    if (!shop_not_existed) {
                        if (Objects.equals(commodity.getMaster(), Const.allShop_existed.get(shopId).getMaster())) {//商品编号属于商家
                            existed_commodity = commodity;
                            commodity_not_existed = false;
                            break;
                        }
                    }
                }
            }
            if (current_user == null) {
                return "Please log in first";
            } else if (identity_illegal) {
                return "Permission denied";
            } else if (shopId_illegal) {
                return "Illegal shop id";
            } else if (shop_not_existed) {
                return "Shop id not exists";
            } else if (commodityId_illegal) {
                return "Illegal commodity id";
            } else if (commodity_not_existed) {
                return "Commodity id not exists";
            } else if (commodityNum_illegal) {
                return "Illegal commodity quantity";
            } else {
                //找到已经存在的
                double price = existed_commodity.getCommodityPrice();
                String name = existed_commodity.getCommodityName();
                //补货的情况
                if (Const.allShop_existed.get(shopId).getCommodities().containsKey(commodityId)) {
                    //找到对应商店的商品
                    existed_commodity = (Commodity) Const.allShop_existed.get(shopId).getCommodities().get(commodityId);
                    existed_commodity.setCommodityNum(existed_commodity.getCommodityNum() + commodityNum);
                } else {//新店铺旧货物情况
                    Commodity new_commodity = new Commodity(shopId, name, price, commodityNum);
                    new_commodity.setCommodityId(existed_commodity.getCommodityId());
                    new_commodity.setMaster(current_user);

                    Const.allShop_existed.get(shopId).getCommodities().put(new_commodity.getCommodityId(), new_commodity);
                    Const.existed_commodities.put(new_commodity.getCommodityId(), new_commodity);
                    Const.allCommodities_existed.put(new_commodity.getShopId() + new_commodity.getCommodityId(), new_commodity);
                }
                return "Put commodity success (commodityId: " + existed_commodity.getCommodityId() + ")";
            }
        } else
            return "Illegal argument count";
    }

    //貌似内部判断完身份再判断是否登录错误了，后续可以取消注释
    //包括cmd参数数量，可以加上注释
    String ListCommodity(String[] cmd) {//库存为0也打印，搜索时不打印
        User current_user = Const.current_user;

        if (cmd.length > 2) {
            return "Illegal argument count";
        }
        if (current_user == null) {
            return "Please log in first";
        }
        if (current_user.getIdentity().equals("Merchant")) {//Merchant
            if (cmd.length == 1) {//查看所有商品
                boolean commodity_not_exists = !Const.masterShop_existed.containsKey(current_user.getCard_number());
                if (commodity_not_exists)//商人没有店铺
                    return "Commodity not exists";
                commodity_not_exists = true;
                HashMap<String, Shop> shopMap = (HashMap<String, Shop>) sortListCommodity_shop(Const.masterShop_existed.get(current_user.getCard_number()));
                for (Shop shop : shopMap.values()) {//在这里判断商店内部有没有商品
                    if (!shop.getCommodities().isEmpty()) //一个为空就看下一个
                        commodity_not_exists = false;
                    else//商店为空
                        continue;
                    Map<String, Commodity> commodityMap = sortListCommodity(shop.getCommodities());//不为空就输出,此处要排序，先按商店，在货物
                    for (Commodity commodity : commodityMap.values()) {
                        System.out.println(shop.getShopId() + ": " + commodity.getCommodityId() + " " + commodity.getCommodityName() + " " + String.format("%.2f", commodity.getCommodityPrice()) + "yuan " + commodity.getCommodityNum());
                    }
                }
                if (commodity_not_exists)
                    return "Commodity not exists";
                return null;

            } else if (cmd.length == 2) {//打印商家某个店铺
                String shopId = cmd[1];
                boolean shopId_illegal = !shopId.matches("^S-[1-9]\\d*$");
                boolean shop_not_exists = !Const.masterShop_existed.get(current_user.getCard_number()).containsKey(shopId);
                boolean commodity_not_exists = true;
                if (!shop_not_exists)
                    if (!Const.allShop_existed.get(shopId).getCommodities().isEmpty())
                        commodity_not_exists = false;

                if (shopId_illegal) {
                    return "Illegal shop id";
                } else if (shop_not_exists) {
                    return "Shop id not exists";
                } else if (commodity_not_exists) {
                    return "Commodity not exists";
                } else {
                    Map<String, Commodity> commodityMap = sortListCommodity(Const.masterShop_existed.get(current_user.getCard_number()).get(shopId).getCommodities());
                    for (Commodity commodity : commodityMap.values()) {
                        System.out.println(shopId + ": " + commodity.getCommodityId() + " " + commodity.getCommodityName() + " " + String.format("%.2f", commodity.getCommodityPrice()) + "yuan " + commodity.getCommodityNum());
                    }
                    return null;
                }
            }
        } else {//客人与管理员
            if (cmd.length == 1) {//打印所有商品
                boolean commodity_not_existed = Const.allCommodities_existed.isEmpty();
                if (commodity_not_existed)
                    return "Commodity not exists";
                else {
                    HashMap<String, Shop> shopMap = (HashMap<String, Shop>) sortListCommodity_shop(Const.allShop_existed);
                    for (Shop shop : shopMap.values()) {
                        Map<String, Commodity> sortedCommodity = sortListCommodity(shop.getCommodities());
                        for (Commodity commodity : sortedCommodity.values()) {
                            System.out.println(shop.getShopId() + ": " + commodity.getCommodityId() + " " + commodity.getCommodityName() + " " + String.format("%.2f", commodity.getCommodityPrice()) + "yuan " + commodity.getCommodityNum());
                        }
                    }
                    return null;
                }
            } else if (cmd.length == 2) {//打印某个店铺
                String shopId = cmd[1];
                boolean shopId_illegal = !shopId.matches("^S-[1-9]\\d*$");
                boolean shop_not_exists = !Const.allShop_existed.containsKey(shopId);
                boolean commodity_not_exists = true;
                if (!shop_not_exists)
                    if (!Const.allShop_existed.get(shopId).getCommodities().isEmpty())
                        commodity_not_exists = false;


                if (shopId_illegal) {
                    return "Illegal shop id";
                } else if (shop_not_exists) {
                    return "Shop id not exists";
                } else if (commodity_not_exists) {
                    return "Commodity not exists";
                } else {
                    Map<String, Commodity> commodityMap = sortListCommodity(Const.allShop_existed.get(shopId).getCommodities());
                    for (Commodity commodity : commodityMap.values()) {
                        System.out.println(shopId + ": " + commodity.getCommodityId() + " " + commodity.getCommodityName() + " " + String.format("%.2f", commodity.getCommodityPrice()) + "yuan " + commodity.getCommodityNum());
                    }
                    return null;
                }
            }
        }
        return null;
    }

    String SearchCommodity(String[] cmd) {
        User current_user = Const.current_user;
        if (cmd.length != 2)
            return "Illegal argument count";
        if (current_user == null)
            return "Please log in first";
        String commodityName = cmd[1];
        boolean commodityName_illegal = !commodityName.matches("^[a-zA-Z][a-zA-Z-_]{0,49}$");
        if (commodityName_illegal) {
            return "Illegal commodity name";
        }
        //String为ShopId+CommodityId
        Map<String, Commodity> commodityMap = new HashMap<>();//

        if (current_user.getIdentity().equals("Merchant")) {//商人只能搜索自己店铺
            for (Commodity commodity : Const.allCommodities_existed.values()) {
                if (commodity.getCommodityName().equals(commodityName)) {
                    if (commodity.getCommodityNum() > 0 && Const.allShop_existed.get(commodity.getShopId()).getMaster().equals(current_user))
                        commodityMap.put(commodity.getShopId() + commodity.getCommodityId(), commodity);
                }
            }

        } else {//客户与管理员
            for (Commodity commodity : Const.allCommodities_existed.values()) {
                if (commodity.getCommodityName().equals(commodityName)) {
                    if (commodity.getCommodityNum() > 0)
                        commodityMap.put(commodity.getShopId() + commodity.getCommodityId(), commodity);
                }
            }
        }
        if (commodityMap.isEmpty()) {
            return "Commodity not exists";
        }
        Map<String, Commodity> commodityMapAns = sortSearchCommodity(commodityMap);
        for (Commodity commodity : commodityMapAns.values()) {
            System.out.println(commodity.getShopId() + ": " + commodity.getCommodityId() + " " + commodity.getCommodityName() + " " + String.format("%.2f", commodity.getCommodityPrice()) + "yuan " + commodity.getCommodityNum());
        }
        return null;
    }

    String BuyCommodity(String[] cmd) {
        User current_user = Const.current_user;
        if (cmd.length != 4) {
            return "Illegal argument count";
        }
        if (current_user == null) {
            return "Please log in first";
        }
        int leftNum = 0, amount = 0;
        String shopId = cmd[1];
        String commodityId = cmd[2];
        if (cmd[3].matches("^[1-9]+[0-9]*"))
            amount = Integer.parseInt(cmd[3]);
        else
            return "Illegal buy quantity";
        boolean permission_illegal = !current_user.getIdentity().equals("Customer");
        boolean shopId_illegal = !shopId.matches("^S-[1-9]\\d*$");
        boolean shopId_not_exists = !Const.allShop_existed.containsKey(shopId);
        boolean commodityId_illegal = !commodityId.matches("^C-[1-9]\\d*$");
        boolean commodityId_not_exist = true;
        if (!shopId_not_exists)
            if (Const.allShop_existed.get(shopId).getCommodities().containsKey(commodityId))
                commodityId_not_exist = false;

        if (!commodityId_not_exist)
            leftNum = ((Commodity) Const.allShop_existed.get(shopId).getCommodities().get(commodityId)).getCommodityNum();
        boolean amount_illegal = amount <= 0 || amount > leftNum;

        if (permission_illegal) {
            return "Permission denied";
        } else if (shopId_illegal) {
            return "Illegal shop id";
        } else if (shopId_not_exists) {
            return "Shop id not exists";
        } else if (commodityId_illegal) {
            return "Illegal commodity id";
        } else if (commodityId_not_exist) {
            return "Commodity id not exists";
        } else if (amount_illegal) {
            return "Illegal buy quantity";
        } else {
            ((Commodity) Const.allShop_existed.get(shopId).getCommodities().get(commodityId)).setCommodityNum(((Commodity) Const.allShop_existed.get(shopId).getCommodities().get(commodityId)).getCommodityNum() - amount);
            Order order = new Order(((Commodity) Const.allShop_existed.get(shopId).getCommodities().get(commodityId)), amount);
            Const.allOrder_existed.put(order.getOrderId(), order);

            return "Buy commodity success (orderId: " + order.getOrderId() + ")";
        }
    }

    String RemoveCommodity(String[] cmd) {
        User current_user = Const.current_user;

        if (cmd.length != 2 && cmd.length != 3) {
            return "Illegal argument count";
        }
        if (current_user == null) {
            return "Please log in first";
        }
        if (current_user.getIdentity().equals("Customer")) {
            return "Permission denied";
        }
        if (cmd.length == 2) {//彻底下架，未来不允许上架:指补货情况（需要考虑在上架那里添加判断条件
            String commodityId = cmd[1];
            boolean commodityId_illegal = !commodityId.matches("C-[1-9]\\d*");
            boolean commodityId_not_exist = true;// 商品编号不存在、商品不属于该商家、商品不属于该店铺
            if (Const.existed_commodities.containsKey(commodityId)) {//货物存在
                //用户是主人或者管理员
                if (current_user.getIdentity().equals("Administrator") || Const.existed_commodities.get(commodityId).getMaster().equals(current_user)) {
                    commodityId_not_exist = false;
                }
            }
            boolean order_not_process = false;
            for (Order order : Const.allOrder_existed.values()) {
                if (order.getCommodity().getCommodityId().equals(commodityId) && order.getCommodity().getShopId().equals(shopId) && order.getOrderStatus() == 0) {
                    order_not_process = true;
                    break;
                }
            }

            if (commodityId_illegal) {
                return "Illegal commodity id";
            } else if (commodityId_not_exist) {
                return "Commodity id not exists";
            } else if (order_not_process) {
                return "Please process order for commodity";
            } else {
                for (Shop shop : Const.allShop_existed.values()) {
                    //只有管理员和此商店主人才可以修改
                    //下面这一步是先清空所有商店里面的信息，如果是管理员，那就全封，商人只封自己的
                    if (current_user.getIdentity().equals("Administrator") || shop.getMaster().equals(current_user)) {//用户名下商店
                        if (shop.getCommodities().containsKey(commodityId)) {//商店有这个货物，进行封禁操作
                            shop.getCommodities().remove(commodityId);//商店要移除
                            Const.allCommodities_existed.remove(shop.getShopId() + commodityId);
                        }
                    }
                }
                //无论商店还有没有，全局id关系删掉
                Const.existed_commodities.remove(commodityId);
                return "Remove commodity success";
            }
        } else {//清空库存，未来还可以上架
            String commodityId = cmd[1];
            String shopId = cmd[2];
            boolean commodityId_illegal = !commodityId.matches("C-[1-9]\\d*");
            boolean shopId_illegal = !shopId.matches("^S-[1-9]\\d*$");
            boolean shopId_not_exist = true;//店铺编号不存在、店铺不属于该商家
            boolean commodityId_not_exist = true;// 商品编号不存在、商品不属于该商家、商品不属于该店铺
            //只有管理员和此商店主人才可以修改
            //如果是管理员且店铺存在
            if (current_user.getIdentity().equals("Administrator") && Const.allShop_existed.containsKey(shopId)) {
                shopId_not_exist = false;
                //如果是商人，店铺存在且属于商人
            } else if (current_user.getIdentity().equals("Merchant") && Const.masterShop_existed.containsKey(current_user.getCard_number())) {//Merchant
                if (Const.masterShop_existed.get(current_user.getCard_number()).containsKey(shopId)) {//店铺属于商人
                    shopId_not_exist = false;
                }
            }

            boolean order_not_process = false;
            for (Order order : Const.allOrder_existed.values()) {
                if (order.getCommodity().getCommodityId().equals(commodityId) && order.getCommodity().getShopId().equals(shopId) && order.getOrderStatus() == 0) {
                    order_not_process = true;
                    break;
                }
            }

            //进行删除该店铺该商品
            //该商店存在 以及 该商店里面存在该货物
            if (Const.allCommodities_existed.containsKey(shopId + commodityId) && !shopId_not_exist) {
                //管理员或者商店主人
                if ((current_user.getIdentity().equals("Administrator") || Const.allShop_existed.get(shopId).getMaster().equals(current_user))) {
//删除放在后面，方便统一
//                    Const.allShop_existed.get(shopId).getCommodities().remove(commodityId);//该商店删除该商品信息
//                    Const.allCommodities_existed.remove(shopId + commodityId);//全局商品清空该商店商品信息
                    commodityId_not_exist = false;
                }
            }
            if (commodityId_illegal)//先处理一部分错误
                return "Illegal commodity id";
            else if (shopId_illegal)
                return "Illegal shop id";
            else if (shopId_not_exist)
                return "Shop id not exists";
            else if (commodityId_not_exist)
                return "Commodity id not exists";
            else if (order_not_process)//
                return "Please process order for commodity";
            else {
                if (Const.allCommodities_existed.containsKey(shopId + commodityId) && !shopId_not_exist) {
                    //管理员或者商店主人
                    if ((current_user.getIdentity().equals("Administrator") || Const.allShop_existed.get(shopId).getMaster().equals(current_user))) {
                        Const.allShop_existed.get(shopId).getCommodities().remove(commodityId);//该商店删除该商品信息
                        Const.allCommodities_existed.remove(shopId + commodityId);//全局商品清空该商店商品信息
                    }
                }
                return "Remove commodity success";
            }

        }
    }

    String PutCommodityBatch(String[] cmd) {
        User current_user = Const.current_user;
        if (cmd.length != 2)
            return "Illegal argument count";
        else if (current_user == null)
            return "Please log in first";
        else if (!current_user.getIdentity().equals("Merchant"))
            return "Permission denied";
        String shopId = cmd[1];

        boolean shopId_illegal = !shopId.matches("S-[1-9]\\d*");
        if (shopId_illegal)
            return "Illegal shop id";

        boolean shop_not_existed = true;
        if (Const.allShop_existed.containsKey(shopId))
            if (Const.allShop_existed.get(shopId).getMaster().equals(current_user))
                shop_not_existed = false;
        if (shop_not_existed)
            return "Shop id not exists";

        List<String> lines = new ArrayList<>();
        String path = "./";
        File f = new File(path, "commodity.txt");
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(f));
            String tempStr;
            int cnt = 1;
            while ((tempStr = reader.readLine()) != null) {
                //System.out.println("line" + line + ": " + tempStr);
                lines.add(tempStr);
                cnt++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {

                }
            }
        }

        lines.forEach(line -> {
            //商品名称 商品价格 商品数量
            String[] each = line.trim().split("\\s+");
            String commodityName = each[0];
            double commodityPrice = Double.parseDouble(each[1]);
            int commodityNum = Integer.parseInt(each[2]);
            //上架新货物
            numOfCommodity++;
            Commodity commodity = new Commodity(shopId, commodityName, commodityPrice, commodityNum);
            commodity.setCommodityId("C-" + numOfCommodity);
            commodity.setMaster(current_user);

            Const.allShop_existed.get(shopId).getCommodities().put(commodity.getCommodityId(), commodity);
            Const.allCommodities_existed.put(commodity.getShopId() + commodity.getCommodityId(), commodity);
            Const.existed_commodities.put(commodity.getCommodityId(), commodity);
            //对commodity排序

        });
        return "Put commodity batch success";
    }

    String favoriteCommodity(String[] cmd) {
        User current_user = Const.current_user;
        if (cmd.length != 4)
            return "Illegal argument count";
        else if (current_user == null)
            return "Please log in first";
        else if (!current_user.getIdentity().equals("Customer"))
            return "Permission denied";
        String shopId = cmd[1];
        String commodityId = cmd[2];
        boolean shopId_illegal = !shopId.matches("^S-[1-9]\\d*$");
        boolean shopId_not_exists = !Const.allShop_existed.containsKey(shopId);
        boolean commodityId_illegal = !commodityId.matches("^C-[1-9]\\d*$");
        boolean commodityId_not_exist = true;
        if (!shopId_not_exists)
            if (Const.allShop_existed.get(shopId).getCommodities().containsKey(commodityId))
                commodityId_not_exist = false;
        if (shopId_illegal) {
            return "Illegal shop id";
        } else if (shopId_not_exists) {
            return "Shop id not exists";
        } else if (commodityId_illegal) {
            return "Illegal commodity id";
        } else if (commodityId_not_exist) {
            return "Commodity id not exists";
        }
        int commodityNum;
        if (cmd[3].matches("^[1-9]+[0-9]*"))
            commodityNum = Integer.parseInt(cmd[3]);
        else
            return "Illegal commodity quantity";
        double commmodityPrice = Const.allCommodities_existed.get(shopId + commodityId).getCommodityPrice();
        if (Const.allFavList_existed.containsKey(current_user.getCard_number()))//存在
            Const.allFavList_existed.get(current_user.getCard_number()).addCommodity(shopId, commodityId, commodityNum, commmodityPrice);
        else {
            FavList f = new FavList(shopId, commodityId, commodityNum, commmodityPrice);
            Const.allFavList_existed.put(current_user.getCard_number(), f);
        }
        return "Favorite commodity success";
    }

    String cancelFavoriteCommodity(String[] cmd) {
        User current_user = Const.current_user;
        if (cmd.length != 3)
            return "Illegal argument count";
        else if (current_user == null)
            return "Please log in first";
        else if (!current_user.getIdentity().equals("Customer"))
            return "Permission denied";
        String shopId = cmd[1];
        String commodityId = cmd[2];
        boolean shopId_illegal = !shopId.matches("^S-[1-9]\\d*$");
        boolean commodityId_illegal = !commodityId.matches("^C-[1-9]\\d*$");
        if (shopId_illegal) {
            return "Illegal shop id";
        } else if (commodityId_illegal) {
            return "Illegal commodity id";
        }
        if (Const.allFavList_existed.containsKey(current_user.getCard_number()))
            if (Const.allFavList_existed.get(current_user.getCard_number()).deleteCommodity(shopId, commodityId))
                return "Cancel favorite commodity success";//有list而且收藏了
        return "Favorite not exists";
    }

    String listFavoriteCommodity(String[] cmd) {
        User current_user = Const.current_user;
        if (cmd.length != 1)
            return "Illegal argument count";
        else if (current_user == null)
            return "Please log in first";
        else if (!current_user.getIdentity().equals("Customer"))
            return "Permission denied";
        if (Const.allFavList_existed.containsKey(current_user.getCard_number()))
            if (!Const.allFavList_existed.get(current_user.getCard_number()).isEmpty()) {
                Const.allFavList_existed.get(current_user.getCard_number()).listCommodities();//有list而且不为空}
                return null;
            }
        return "Favorite not exists";
    }

    String uploadFavoriteCommodity(String[] cmd) {
        User current_user = Const.current_user;
        String path;
        String fileName;
        if (cmd.length != 2)
            return "Illegal argument count";
        else if (current_user == null)
            return "Please log in first";
        else if (!current_user.getIdentity().equals("Customer"))
            return "Permission denied";
        if (cmd[1].charAt(0) == '.')//已经有 ./ 了
            path = "./data/" + cmd[1].substring(2);
        else
            path = "./data/" + cmd[1];
        fileName = path.substring(path.lastIndexOf("/") + 1);
        path = path.substring(0, path.lastIndexOf("/"));
        if (Const.allFavList_existed.containsKey(current_user.getCard_number()))
            if (!Const.allFavList_existed.get(current_user.getCard_number()).isEmpty()) {
                FavList favList = Const.allFavList_existed.get(current_user.getCard_number());
                File file = new File(path + '/' + fileName);//我们在该类的位置创建一个新文件
                File folder = new File(path);
                if (!folder.exists() && !folder.isDirectory())//文件夹不存存在就新建
                    folder.mkdirs();
                if (!file.exists()) //不存在就新建文件
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        return "File operation failed";
                    }
                //开始序列化
                try {
                    OutputStream ops = new FileOutputStream(file);
                    ObjectOutputStream oos = new ObjectOutputStream(ops);
                    oos.writeObject(favList);
                    oos.close();
                    ops.close();
                    return "Upload favorite commodity success";
                } catch (Exception e) {
                    return "File operation failed";
                }
            }
        return "Favorite not exists";
    }

    String readFavoriteCommodity(String[] cmd) {
        User current_user = Const.current_user;
        String path;
        String fileName;
        if (cmd.length != 2)
            return "Illegal argument count";
        else if (current_user == null)
            return "Please log in first";
        else if (!current_user.getIdentity().equals("Customer"))
            return "Permission denied";
        if (cmd[1].charAt(0) == '.')//已经有 ./ 了
            path = "./data/" + cmd[1].substring(2);
        else
            path = "./data/" + cmd[1];
        fileName = path.substring(path.lastIndexOf("/") + 1);
        path = path.substring(0, path.lastIndexOf("/"));
        File file = new File(path + '/' + fileName);//我们在该类的位置创建一个新文件
        File folder = new File(path);
        if (!folder.exists() && !folder.isDirectory())//文件夹不存存在就新建
            return "File not exists";
        if (!file.exists()) //不存在就新建文件
            return "File not exists";
        if (Const.allFavList_existed.containsKey(current_user.getCard_number())) {
            if (!Const.allFavList_existed.get(current_user.getCard_number()).isEmpty()) {
                FavList favList = Const.allFavList_existed.get(current_user.getCard_number());
                //开始反序列化
                try {
                    InputStream in = new FileInputStream(file);
                    ObjectInputStream input = new ObjectInputStream(in);
                    FavList addList = (FavList) input.readObject();
                    for (Commodity c : addList.getCommodities()) {
                        favList.addCommodity(c.getShopId(), c.getCommodityId(), c.getCommodityNum(), c.getCommodityPrice());
                    }
                    input.close();
                    in.close();
                } catch (Exception e) {
                    return "File operation failed";
                }
            }
        } else {
            FavList favList = new FavList();
            try {
                InputStream in = new FileInputStream(file);
                ObjectInputStream input = new ObjectInputStream(in);
                FavList addList = (FavList) input.readObject();
                for (Commodity c : addList.getCommodities()) {
                    favList.addCommodity(c.getShopId(), c.getCommodityId(), c.getCommodityNum(), c.getCommodityPrice());
                }
                input.close();
                in.close();
                Const.allFavList_existed.put(current_user.getCard_number(), favList);
            } catch (Exception e) {
                return "File operation failed";
            }
        }
        return "Read favorite commodity success";
    }

    String buyFavoriteCommodity(String[] cmd) {
        User current_user = Const.current_user;
        if (cmd.length != 1)
            return "Illegal argument count";
        else if (current_user == null)
            return "Please log in first";
        else if (!current_user.getIdentity().equals("Customer"))
            return "Permission denied";
        if (Const.allFavList_existed.containsKey(current_user.getCard_number()))
            if (!Const.allFavList_existed.get(current_user.getCard_number()).isEmpty()) {
                Const.allFavList_existed.get(current_user.getCard_number()).buyCommodities();
                return null;
            }
        return "Favorite not exists";
    }
}